<template>
	<div>
		<el-table :data="tbdata" style="width: 100%" stripe highlight-current-row height="600" empty-text="暂时没有数据">
			<el-table-column type="selection" fixed="left"></el-table-column>
			<el-table-column label="学生学号" prop="studentid" sortable></el-table-column>
			<el-table-column label="学生姓名" prop="studentname" sortable align="center"></el-table-column>
			<el-table-column label="课程编号" prop="courseid" sortable align="center"></el-table-column>
			<el-table-column label="课程名" prop="coursename" sortable align="center"></el-table-column>
			<el-table-column label="课程成绩" prop="score" sortable align="center"></el-table-column>
			<el-table-column
				prop="score"
				label="成绩等级"
				width="100"
				:filters="[{ text: '不及格', value: '不及格' }, { text: '及格', value: '及格' }, { text: '良好', value: '良好' }, { text: '优秀', value: '优秀' }]"
				:filter-method="filterTag"
				filter-placement="bottom-end"
			>
				<template slot-scope="scope">
					<el-tag :type="tagType(scope.row.score)" disable-transitions>{{ scope.row.score | scoreFilter }}</el-tag>
				</template>
			</el-table-column>
			<el-table-column align="right" fixed="right" width="200">
				<template slot="header" slot-scope="scope">
					<el-select v-model="searchType" placeholder="请选择" size="mini" style="width: 90px;padding: 0;">
						<el-option value="学号"></el-option>
						<el-option value="姓名"></el-option>
						<el-option value="课程编号"></el-option>
						<el-option value="课程"></el-option>
					</el-select>
					<el-input v-model="search" size="mini" placeholder="输入关键字搜索" style="padding: 0; width: 120px;" />
				</template>
				<template slot-scope="scope">
					<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">Edit</el-button>
					<el-button size="mini" type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.$index, scope.row)"></el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-dialog :title="dialogType == 'create' ? '创建成绩' : '编辑成绩'" :visible.sync="dialogFormVisible">
			<el-form :model="form" v-if="form">
				<template v-if="dialogType == 'create'">
					<el-form-item label="学生" :label-width="formLabelWidth">
						<el-select
							v-model="form.studentid"
							remote
							filterable
							default-first-option
							placeholder="请输入学生姓名"
							:remote-method="remoteMethod"
							:loading="loading"
							:disabled="dialogType == 'edit'"
						>
							<el-option v-for="item in students" :key="item.id" :label="'学号:'+item.id + ' 姓名:' + item.name" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
				</template>
				<template v-else>
					<el-form-item label="学生" :label-width="formLabelWidth">
						<el-select
							v-model="form.studentname"
							remote
							filterable
							default-first-option
							placeholder="请输入学生姓名"
							:remote-method="remoteMethod"
							:loading="loading"
							:disabled="dialogType == 'edit'"
						>
							<el-option v-for="item in students" :key="item.id" :label="item.name" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
				</template>
				<el-form-item label="课程" :label-width="formLabelWidth">
					<el-select v-model="form.courseid" placeholder="请选择" :disabled="dialogType == 'edit'">
						<el-option v-for="item in $store.state.courses" :key="item.id" :label="'课程编号:'+item.id +' 课程名:'+ item.name" :value="item.id"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="成绩" :label-width="formLabelWidth"><el-input v-model="form.score" autocomplete="off"></el-input></el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button
					@click="
						dialogFormVisible = false;
						form = null;
					"
				>
					取 消
				</el-button>
				<el-button type="primary" @click="formConfirm">确 定</el-button>
			</div>
		</el-dialog>
		<el-button icon="el-icon-circle-plus-outline" type="primary" @click="createGrade">新建成绩</el-button>
		<el-button icon="el-icon-refresh-right" type="infor" @click="getGrades"></el-button>
	</div>
</template>

<script>
var scoreType = [
	{
		max: 59,
		type: '不及格'
	},
	{
		max: 70,
		type: '及格'
	},
	{
		max: 84,
		type: '良好'
	},
	{
		max: 100,
		type: '优秀'
	}
];
export default {
	data() {
		return {
			tableData: [],
			search: '',
			dialogFormVisible: false,
			form: null,
			formLabelWidth: '120px',
			dialogType: 'edit',
			loading: false,
			students: [],
			searchType: '学号'
		};
	},
	mounted: function() {
		this.getGrades();
	},
	filters: {
		scoreFilter(value) {
			for (let i in scoreType) {
				if (value < scoreType[i].max) return scoreType[i].type;
			}
			return '未知';
		}
	},
	methods: {
		/**
		 * 点击编辑按钮触发,格式化数据，打开表单
		 *
		 * @param {Number} index 数据中的角标
		 * @param {Object} row 数据对象
		 */
		handleEdit(index, row) {
			let that = this;
			if (that.dialogFormVisible) return;
			if (that.dialogType != 'edit') that.dialogType = 'edit';
			that.form = row;
			that.dialogFormVisible = true;
		},
		getGrades() {
			let that = this;
			that.tableData = [];
			that.axios
				.get(that.$store.state.serverHost + '/grade/getGrades/')
				.then(res => {
					let reg = new RegExp("'", 'g');
					for (let i in res.data) {
						let data = JSON.parse(res.data[i].replace('"', '').replace(reg, '"'));
						that.tableData.push(data);
					}
					// that.$store.commit('updataCourse', that.tableData);
				})
				.catch(e => {
					that.$message.error('获取数据失败');
				});
		},
		handleDelete(index, row) {
			this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
			  this.axios.post(this.$store.state.serverHost+'/grade/deleteGrade/',row)
          .then(res=>{
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getGrades()
          })
			});
		},
		formConfirm() {
			let that = this;
			if (that.dialogType == 'create') {
				that.axios
					.post(that.$store.state.serverHost + '/grade/addGrade/', that.form)
					.then(res => {
						if (res.data == '添加失败') that.$message.error('添加失败');
						if (res.data == '该成绩已存在') that.$message.error('该成绩已存在');
						that.getGrades()
					})
					.catch(e => {
						that.$message.error('添加失败');
					});
			} else {
        console.log(that.form);
        that.axios
					.post(that.$store.state.serverHost + '/grade/changeGrade/', that.form)
					.then(res => {
            console.log(res);
            if (res.data == '修改成功') that.$message.success('修改成功');
					})
					.catch(e => {
						that.$message.error('修改失败');
					});
			}
			that.dialogFormVisible = false;
			that.form = null;
			setTimeout(() => {
				that.getGrades();
			}, 200);
		},
		createGrade() {
			let that = this;
			if (that.dialogFormVisible) return;
			if (that.dialogType != 'create') that.dialogType = 'create';
			that.form = {
				studentid: '',
				courseid: '',
				score: ''
			};
			that.dialogFormVisible = true;
		},
		remoteMethod(query) {
			if (query == '') return;
			this.loading = true;
			setTimeout(() => {
				this.students = this.$store.state.students.filter(item => {
					return item.name.indexOf(query) > -1;
				});
				this.loading = false;
			}, 200);
		},
		tagType(value) {
			for (let i in scoreType) {
				if (value < scoreType[i].max) {
					switch (scoreType[i].type) {
						case '不及格':
							return 'danger';
						case '及格':
							return 'warning';
						case '良好':
							return '';
						case '优秀':
							return 'success';
					}
				}
			}
			return 'info';
		},
		filterTag(value, row) {
			for (let i in scoreType) {
				if (row.score < scoreType[i].max) {
					return scoreType[i].type == value;
				}
			}
		}
	},
	computed: {
		tbdata() {
			let that = this;
			let ageFilter = that.$options.filters['ageFilter'];
			return that.tableData.filter(data => {
				if (!that.search) return true;
				switch (that.searchType) {
					case '姓名':
						return JSON.stringify(data.studentname).includes(that.search);
					case '课程编号':
						return JSON.stringify(data.courseid).includes(that.search);
					case '课程':
						return JSON.stringify(data.coursename).includes(that.search);
					default:
						return JSON.stringify(data.studentid).includes(that.search);
				}
			});
		}
	}
};
</script>

<style scoped></style>
